import { MatchCacheService } from 'src/modules/match/match.cache.service';
import { Injectable } from '@nestjs/common';
// import { MatchService } from '../match.service';
import logger from 'src/common/utils/log';
import { GroupService } from 'src/modules/group/group.service';
import { CategoryService } from 'src/modules/category/category.service';
import { EventService } from 'src/modules/event/event.service';
import { StageService } from 'src/modules/stage/stage.service';
import { TournamentService } from 'src/modules/tournament/tournament.service';
import {
  MatchStatusEnum,
  StagePlayerSourceTypeEnum,
  StageStatusEnum,
  StageTypeEnum,
  TeamEventList,
} from 'src/common/constant/enums';
import { EndMatchDto } from './dto/endMatch.dto';
import { EventToPlayer } from 'src/modules/event-to-player/entities/event-to-player.entity';
import { GroupPlayerScore } from 'src/modules/group-player-score/entities/group-player-score.entity';
import { EventToPlayerService } from 'src/modules/event-to-player/event-to-player.service';
import { Group } from 'src/modules/group/entities/group.entity';
import { Stage } from 'src/modules/stage/entities/stage.entity';
import { matchScoreHelper } from './helpers/match-score-helper';
import { GroupPlayerScoreService } from 'src/modules/group-player-score/group-player-score.service';
import { ConfirmPlayerE2PService } from 'src/modules/event-to-player/services/confirmPlayerE2P.service';
import { MatchService } from 'src/modules/match/match.service';
import { MatchInfo } from 'src/modules/match/entities/match.entity';
import { StageDetailService } from '../stage-detail/stage-detail.service';
import { EventToPlayerCacheService } from 'src/modules/event-to-player/event-to-player.cache.service';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { StageCacheService } from 'src/modules/stage/stage.cache.service';

type groupProcessInfo = {
  finished: boolean;
  winners?: GroupPlayerScore[];
  losers?: GroupPlayerScore[];
};
@Injectable()
export class MatchEndService {
  constructor(
    private readonly matchService: MatchService,
    private readonly groupService: GroupService,
    private readonly stageService: StageService,
    private readonly eventService: EventService,
    private readonly categoryService: CategoryService,
    private readonly tournamentService: TournamentService,
    private readonly eventToPlayerService: EventToPlayerService,
    private readonly groupPlayerScoreService: GroupPlayerScoreService,
    private readonly confirmPlayerService: ConfirmPlayerE2PService,
    private readonly stageDetailService: StageDetailService,
    private readonly matchCacheService: MatchCacheService,
    private readonly eventToPlayerCacheService: EventToPlayerCacheService,
    private eventEmitter: EventEmitter2,
    private readonly stageCacheService: StageCacheService,
  ) {}
  async endMatch(endMatchDto: EndMatchDto) {
    const { id, homePlayerRally, awayPlayerRally } = endMatchDto;
    const matchInfo = await this.matchService.findById(id);
    matchInfo.homePlayerRally = homePlayerRally;
    matchInfo.awayPlayerRally = awayPlayerRally;
    matchInfo.winnerId =
      homePlayerRally > awayPlayerRally
        ? matchInfo.homePlayerId
        : matchInfo.awayPlayerId;
    matchInfo.status = MatchStatusEnum.Finished;
    matchInfo.actualEnd = new Date();
    matchInfo.updateBy = endMatchDto?.user?.id || 1;
    await this.matchService.update(id, matchInfo);
    const e2pList = await this.eventToPlayerCacheService.getListByEventId(
      matchInfo.eventId,
    );
    // 如果是团体赛，则需要更新上级比赛的比分
    if (matchInfo.isTeamMatch && matchInfo.subMatchId) {
      // 如果是团队赛，需要更新上级比赛的比分
      await this.updateTeamMatchScore(matchInfo, e2pList);
    } else {
      //如果是淘汰赛，则需要更新胜者赛和败者赛
      await this.updateNextWinnerLoserMatch(matchInfo, e2pList);
      //更新group 和stage的数据即和比赛相关联的数据
      await this.updateMathGroupAndStageInfo(matchInfo, true);
    }
    await this.eventToPlayerCacheService.handleEventToPlayerUpdate(e2pList);
    await this.matchCacheService.handleMatchUpdate(matchInfo);
    await this.stageCacheService.handleStageUpdate({
      id: matchInfo.stageId,
    });
    // this.eventEmitter.emit('match.playMatchUpdate', matchInfo.tournamentId);
  }

  private async updateTeamMatchScore(
    curMatchInfo: MatchInfo,
    e2pList: EventToPlayer[] = [],
  ) {
    // 更新group 和stage的数据即和比赛相关联的数据
    // 根据当前比赛的胜负，更新主比赛的比分
    // 判断父比赛是否所有子比赛都已经结束，如果结束，则更新父比赛的winner
    // 更新group 和stage的数据即和比赛相关联的数据
    const { subMatchId, mustFinishMaxCountMatch } = curMatchInfo;
    // const teamWinner = winner.split('-')[0];
    // const parentMatchDetail =
    //   await this.matchService.getMatchDetail(subMatchId);
    const parentMatchDetail = await this.matchService.findById(subMatchId);
    // const e2pList = await this.eventToPlayerCacheService.getListByEventId(
    //   parentMatchDetail.eventId,
    // );
    const { homePlayerId, awayPlayerId, subMatchInfos } = parentMatchDetail;
    const homePlayer = e2pList.find((v) => v.id === homePlayerId);
    const awayPlayer = e2pList.find((v) => v.id === awayPlayerId);
    let homePlayerRally = 0;
    let awayPlayerRally = 0;
    subMatchInfos.forEach((subMatchInfo) => {
      subMatchInfo.winner = e2pList.find((v) => v.id === subMatchInfo.winnerId);
      if (
        subMatchInfo.winner?.registrationIndex?.split('-')[0] ===
        homePlayer.registrationIndex
      ) {
        homePlayerRally += 1;
      } else if (
        subMatchInfo.winner?.registrationIndex?.split('-')[0] ===
        awayPlayer.registrationIndex
      ) {
        awayPlayerRally += 1;
      }
    });
    parentMatchDetail.homePlayerRally = homePlayerRally;
    parentMatchDetail.awayPlayerRally = awayPlayerRally;

    // 判断父比赛是否所有子比赛都已经结束，如果结束，则更新父比赛的winner
    const unfinishedMatch = subMatchInfos.find(
      (subMatchInfo) => subMatchInfo.status !== MatchStatusEnum.Finished,
    );
    const needUpdateSubMatches = [];
    // 如果mustFinishMaxCountGame === true, 则如果存在unfinishedMatch 则不更新父比赛的winner
    if (mustFinishMaxCountMatch === true) {
      if (unfinishedMatch) {
        parentMatchDetail.status = MatchStatusEnum.InProgress;
      } else {
        this.finishAndAddWinnerToMatch(parentMatchDetail);
      }
    } else {
      // 当有人完成了需要的比分，则结束
      const minWinGames = Math.ceil((subMatchInfos.length + 1) / 2);
      if (
        parentMatchDetail.homePlayerRally >= minWinGames ||
        parentMatchDetail.awayPlayerRally >= minWinGames
      ) {
        this.finishAndAddWinnerToMatch(parentMatchDetail);
        subMatchInfos.forEach((subMatchInfo) => {
          if (subMatchInfo.status !== MatchStatusEnum.Finished) {
            subMatchInfo.status = MatchStatusEnum.Finished;
            subMatchInfo.actualEnd = new Date();
            needUpdateSubMatches.push(subMatchInfo);
          }
        });
      } else {
        parentMatchDetail.status = MatchStatusEnum.InProgress;
      }
    }
    // 更新付比赛
    await this.matchService.update(parentMatchDetail.id, parentMatchDetail);
    // 删除这个比赛的缓存，这个缓存在更新比分的时候会用到
    await this.matchCacheService.deleteMatch(parentMatchDetail.id);
    // 更新子比赛
    if (needUpdateSubMatches.length) {
      await this.matchService.saveList(needUpdateSubMatches);
    }
    //如果是淘汰赛，则需要更新胜者赛和败者赛
    await this.updateNextWinnerLoserMatch(parentMatchDetail, e2pList);
    //更新group 和stage的数据即和比赛相关联的数据
    await this.updateMathGroupAndStageInfo(parentMatchDetail, true);
  }

  private finishAndAddWinnerToMatch(match: MatchInfo) {
    match.winnerId =
      match.homePlayerRally > match.awayPlayerRally
        ? match.homePlayerId
        : match.awayPlayerId;
    match.status = MatchStatusEnum.Finished;
    match.actualEnd = new Date();
  }
  // 修改比赛上级对象的状态(group/stage/event/category/tournament)
  private async changeUplevelStatus(matchDetail: MatchInfo) {
    const { groupId, stageId, eventId, categoryId, tournamentId } = matchDetail;
    logger.info(
      `changeUplevelStatus ${groupId}, ${stageId}, ${eventId}, ${categoryId}, ${tournamentId}`,
    );
    const isGroupFinish = await this.groupService.checkFinish(groupId);
    if (!isGroupFinish) {
      return 'match';
    }
    const isStageFinish = await this.stageService.checkFinish(stageId);
    if (!isStageFinish) {
      return 'group';
    }
    const isEventFinish = await this.eventService.checkFinish(eventId);
    if (!isEventFinish) {
      return 'stage';
    }
    const isCategoryFinish = await this.categoryService.checkFinish(categoryId);
    if (!isCategoryFinish) {
      return 'event';
    }
    const isTournamentFinish =
      await this.tournamentService.checkFinish(tournamentId);
    if (!isTournamentFinish) {
      return 'category';
    }
    return 'tournament';
  }
  private async updateNextWinnerLoserMatch(
    curMatchInfo: MatchInfo,
    e2pListParam: EventToPlayer[],
  ) {
    let e2pList = e2pListParam;
    const createOrUpdateMatchPlayer = async (
      nextMatch: MatchInfo,
      playerInfo: Partial<EventToPlayer>,
      isHomePlayer: boolean,
    ) => {
      const newPlayerInfo = { ...playerInfo };
      delete newPlayerInfo.id; // 删除id，创建一条新的数据
      if (nextMatch.subMatchId) {// 子比赛不更新选手数据
        delete newPlayerInfo.player1Id;
        delete newPlayerInfo.player2Id;
        delete newPlayerInfo.player1Name;
        delete newPlayerInfo.player2Name;
      }
      const playerIdField = isHomePlayer ? 'homePlayerId' : 'awayPlayerId';
      if (nextMatch[playerIdField]) {
        // 已经有选手数据了，更新这条数据
        logger.info(
          `updateNextWinnerLoserMatch update player ${nextMatch[playerIdField]} to match ${nextMatch.id}`,
        );
        const playerId = nextMatch[playerIdField];
        await this.eventToPlayerService.update(playerId, newPlayerInfo);
      } else {
        // 创建一条新数据
        const upgradePlayer =
          await this.eventToPlayerService.create(newPlayerInfo); //创建一个新的E2P，保证淘汰赛子比赛也可以自由指定选手
        logger.info(
          `updateNextWinnerLoserMatch create player ${upgradePlayer.id} to match ${nextMatch.id}`,
        );
        nextMatch[playerIdField] = upgradePlayer.id;
      }
    };
    const setPlayerToSubMatch = async (
      nextMatch,
      upgradePlayerInfoInfo: Partial<EventToPlayer>,
      isHomePlayer,
    ) => {
      if (nextMatch.subMatchInfos?.length) {
        const isHomePlayerUpgrade =
          curMatchInfo.homePlayerId === upgradePlayerInfoInfo.id;
        // nextMatch.subMatchInfos.forEach((subMatchInfo) => {
        for (const subMatchInfo of nextMatch.subMatchInfos) {
          //如果子比赛已经有homePlayerId 或者 awayPlayerId 则跳过
          subMatchInfo.updateBy = curMatchInfo.updateBy;
          const subMatchOrder = subMatchInfo.subMatchOrder;
          // 将上一场子比赛的人落在这场比赛上
          if (curMatchInfo.subMatchInfos?.length) {
            const curSubMatch = curMatchInfo.subMatchInfos.find((v) => {
              return v.subMatchOrder === subMatchOrder;
            });
            let originPlayerE2P = isHomePlayerUpgrade
              ? curSubMatch.homePlayer
              : curSubMatch.awayPlayer;
            if (!originPlayerE2P) {
              // 先看看之前有没有查出来，没有的话就查一道
              const _upgradePlayerId = isHomePlayerUpgrade
                ? curSubMatch.homePlayerId
                : curSubMatch.awayPlayerId;
              originPlayerE2P =
                await this.eventToPlayerService.findOne(_upgradePlayerId);
            }
            await createOrUpdateMatchPlayer(
              subMatchInfo as MatchInfo,
              originPlayerE2P,
              isHomePlayer,
            );
          }
        }
      }
    };
    const setPlayer = async (
      nextMatch: MatchInfo,
      upgradePlayerInfo: Partial<EventToPlayer>,
      isHomePlayer: boolean,
    ) => {
      const isByePlayer = upgradePlayerInfo.isByePlayer;
      if (isByePlayer) {
        nextMatch.hasByePlayer = isByePlayer;
      }
      nextMatch.updateBy = curMatchInfo.updateBy;
      await createOrUpdateMatchPlayer(
        nextMatch,
        upgradePlayerInfo,
        isHomePlayer,
      );
      await setPlayerToSubMatch(nextMatch, upgradePlayerInfo, isHomePlayer);
      await this.eventToPlayerCacheService.handleEventToPlayerUpdate([
        {
          eventId: nextMatch.eventId,
        } as any,
      ]);
      e2pList = await this.eventToPlayerCacheService.getListByEventId(
        nextMatch.eventId,
      );
    };
    if (!curMatchInfo.winnerId) {
      return; // 没有胜者 则不更新下一场
    }
    if (curMatchInfo.nextWinnerMatchIndex) {
      const nextWinnerMatch =
        await this.matchService.getMatchByGroupIdAndGroupMatchIndex(
          curMatchInfo.groupId,
          curMatchInfo.nextWinnerMatchIndex,
        );
      logger.info(
        `start set next winner match player matchId: ${nextWinnerMatch.id} playerId: ${curMatchInfo.winnerId}`,
      );
      await setPlayer(
        nextWinnerMatch,
        // { id: curMatchInfo.winnerId },
        e2pList.find((v) => v.id === curMatchInfo.winnerId),
        curMatchInfo.groupMatchIndex % 2 === 1, // 奇数位填充homePlayer 否则填充awayPlayer
      ); // 更新胜者赛
      await this.matchService.save(nextWinnerMatch);
    }
    if (curMatchInfo.nextLoserMatchIndex) {
      const loserId =
        curMatchInfo.winnerId === curMatchInfo.homePlayerId
          ? curMatchInfo.awayPlayerId
          : curMatchInfo.homePlayerId;
      const nextLoserMatch =
        await this.matchService.getMatchByGroupIdAndGroupMatchIndex(
          curMatchInfo.groupId,
          curMatchInfo.nextLoserMatchIndex,
        );
      logger.info(
        `start set next loser match player matchId: ${nextLoserMatch.id} playerId: ${loserId}`,
      );
      await setPlayer(
        nextLoserMatch,
        // { id: loserId },
        e2pList.find((v) => v.id === loserId),
        curMatchInfo.groupMatchIndex % 2 === 1,
      ); // 奇数位填充homePlayer 否则填充awayPlayer); // 更新败者赛
      const savedNextLoserMatch = await this.matchService.save(nextLoserMatch);
      // 需要检查nextLoserMatch 是否包含byePlayer, 如果包含则直接将byePlayer 则调用endMatch 直接将其结束
      // 测试：1. 普通4近4比赛，设置一个轮空，检查第一轮结束后是否直接产生第三名，2.团赛4近4比赛，设置一个轮空，检查第一轮结束后是否直接产生第三名
      const homePlayer = e2pList.find(
        (v) => v.id === savedNextLoserMatch.homePlayerId,
      );
      const awayPlayer = e2pList.find(
        (v) => v.id === savedNextLoserMatch.awayPlayerId,
      );
      const hasByePlayer = homePlayer?.isByePlayer || awayPlayer?.isByePlayer;
      if (
        savedNextLoserMatch.homePlayerId &&
        savedNextLoserMatch.awayPlayerId &&
        hasByePlayer
      ) {
        const winnerRally = 2;
        await this.endMatch({
          id: nextLoserMatch.id,
          homePlayerRally: homePlayer.isByePlayer ? 0 : winnerRally,
          awayPlayerRally: awayPlayer.isByePlayer ? 0 : winnerRally,
          user: { id: curMatchInfo.updateBy } as any,
        });
      }
    }
  }
  private async updateMathGroupAndStageInfo(
    curMatchInfo: MatchInfo,
    isFinished: boolean,
  ) {
    logger.info(
      `updateMathGroupAndStageInfo start... curMatchInfo: ${curMatchInfo.id} isFinished: ${isFinished}`,
    );
    await this.finishStage(curMatchInfo);
    await this.changeUplevelStatus(curMatchInfo);
  }

  private async finishStage(matchDetail: MatchInfo) {
    const stageDetail =
      await this.stageDetailService.getStageDetailWithPlayerInfo(
        matchDetail.stageId,
      ); // 获取stageDetail 包含group信息
    const { type: stageType } = stageDetail;
    const winnerCount =
      stageType === StageTypeEnum.Elimination
        ? stageDetail.eliminationWinnerCount
        : stageDetail.roundGroupWinnerCount;
    const { eventId } = stageDetail;

    // const stageProcessInfo =
    //   await this.stageService.getStageProcessInfo(stageId);
    // 拉去整个stage 的全部信息，计算当前stage是否结束
    // const stageDetail = await this.stageService.getStageDetail(stageId);
    await this.updateGroupPlayerScores(matchDetail, stageDetail);
    const { groups } = stageDetail;
    // 检查group是否全部完成，以及每个group的胜者
    const groupProcessInfos: Array<groupProcessInfo> = [];
    groups.forEach((group) => {
      const { matchInfos, groupPlayerScores } = group;
      const unfinishedMatch = matchInfos.find(
        (matchInfo) => matchInfo.status !== MatchStatusEnum.Finished,
      );
      if (unfinishedMatch) {
        // 存在未完成的比赛
        groupProcessInfos.push({ finished: false });
        return;
      }
      // 所有比赛都已经结束，从groupPlayerScores中抽取胜利者，给到下一个stage
      const groupProcessInfo = { finished: true, winners: [], losers: [] };
      if (stageType === StageTypeEnum.Elimination) {
        const sortedScore = groupPlayerScores.sort((a, b) => {
          return b.eliminationPosition - a.eliminationPosition;
        });
        const winners = sortedScore.slice(0, winnerCount);
        const losers = sortedScore.slice(winnerCount);
        groupProcessInfo.winners = winners;
        groupProcessInfo.losers = losers;
      } else {
        const sortedScore = groupPlayerScores.sort((a, b) => {
          const aNetWins = a.winMatchCount - a.loseMatchCount;
          const bNetWins = b.winMatchCount - b.loseMatchCount;
          return bNetWins - aNetWins;
        });

        const winners = sortedScore.slice(0, winnerCount);
        const losers = sortedScore.slice(winnerCount);
        groupProcessInfo.winners = winners;
        groupProcessInfo.losers = losers;
        // groupProcessInfo.winners = winners.map((v) => {
        //   return v.player.registrationIndex;
        // });
      }
      groupProcessInfos.push(groupProcessInfo);
    });
    // 将winners添加到nextStagePlayers中
    const isStageFinished = groupProcessInfos.every((info) => info.finished);
    // 更新stage 的状态
    await this.stageService.update(stageDetail.id, {
      status: isStageFinished
        ? StageStatusEnum.Finished
        : StageStatusEnum.InProgress,
    });
    if (isStageFinished) {
      await this.startNextRelationStage(
        eventId,
        stageDetail.id,
        groupProcessInfos,
      );
    }
  }
  async startNextRelationStage(
    eventId: number,
    currentStageId: number,
    groupProcessInfos: Array<groupProcessInfo>,
  ) {
    logger.info('startNextRelationStage is not supported for now');
    return;
    const relationStages =
      await this.stageService.listBySourcePlayerStageId(currentStageId);
    if (!relationStages.length) {
      logger.info(`没有后续相关stage,返回`);
      return;
    }
    logger.info(
      `${relationStages.length}个stage 与 ${currentStageId}: ${relationStages.map(
        (v) => {
          return ' id:' + v.id + ' playerSourceType:' + v.playerSourceType;
        },
      )}`,
    );
    const promiseList = [];
    relationStages.forEach((relationStage) => {
      const { playerSourceType, playerCount } = relationStage;
      const playersHasNextStage = []; // 记录已经有下一轮的选手
      // const promotionPlayerCountOfGroup =
      //   playerCount / groupProcessInfos.length; // 每组自动晋级自动晋级
      // logger.info(
      //   `自动晋级人数 ${playerCount}, 每个group ${promotionPlayerCountOfGroup}人`,
      // );
      if (playerSourceType === StagePlayerSourceTypeEnum.winner) {
        const nextStagePlayers = groupProcessInfos
          .map((v) => v.winners)
          .flat()
          .sort((a, b) => b.ranking - a.ranking)
          .slice(0, playerCount);
        if (nextStagePlayers.length) {
          playersHasNextStage.push(...nextStagePlayers);
          promiseList.push(
            this.startNextStage(eventId, relationStage, nextStagePlayers),
          );
        }
      } else if (playerSourceType === StagePlayerSourceTypeEnum.loser) {
        const nextStagePlayers = groupProcessInfos
          .map((v) => v.losers)
          .flat()
          .sort((a, b) => b.ranking - a.ranking)
          .slice(0, playerCount);
        if (nextStagePlayers.length) {
          playersHasNextStage.push(...nextStagePlayers);
          promiseList.push(
            this.startNextStage(eventId, relationStage, nextStagePlayers),
          );
        }
      }
    });
    await Promise.all(promiseList);
    // const countOfTotalPlayers = groupProcessInfos.reduce((total, item) => {
    //   return total + item.losers.length + item.winners.length;
    // }, 0);
    // const playersDontHaveNextStageCount =
    //   countOfTotalPlayers - playersHasNextStage.length;
    // if (playersDontHaveNextStageCount > 0) {
    //   logger.info(`${playersDontHaveNextStageCount}个选手不会参与后边的比赛`);
    //   await this.playerSignupService.knockoutPlayers(
    //     eventId,
    //     playersHasNextStage.map((v) => v.player.id),
    //   );
    // }
    logger.info('endNextRelationStage');
  }
  async startNextStage(
    eventId: number,
    stageInfo: Stage,
    players: GroupPlayerScore[],
  ) {
    // const nextStageOrder = stageOrderInEvent + 1;
    logger.info('start startNextStage');
    const nextStageOrder = stageInfo.stageOrderInEvent;
    const allWinnersWithPlayerInfo =
      await this.groupPlayerScoreService.listByIds(players.map((v) => v.id));
    const customE2PConfig = {};
    // const nextPlayerIds = [];
    allWinnersWithPlayerInfo.map((winnerScoreInfo, order) => {
      const player = winnerScoreInfo.player;
      const playerId = player.player1Id;
      const player2Id = player.player2Id;
      const isByePlayer = player.isByePlayer;
      if (isByePlayer) {
        // logger.info(`${player.id}:  playerId || player2Id is false maybe they are bye player`);
        return;
      }
      customE2PConfig[order] = [playerId];
      // nextPlayerIds.push(playerId);
      if (player2Id) {
        customE2PConfig[order].push(player2Id);
        // nextPlayerIds.push(player2Id);
      }
    });
    logger.info(
      `开始给${stageInfo.id} stage 添加选手, 共 ${Object.keys(customE2PConfig).length} 个选手`,
    );
    // await this.playerSignupService.knockoutPlayers(eventId, nextPlayerIds); // 将其与选手进行淘汰
    await this.confirmPlayerService.confirmPlayerE2P(
      eventId,
      'custom',
      customE2PConfig,
      nextStageOrder,
    );
    logger.info('end startNextStage');
  }

  // 如果当前比赛结束后存在人员晋级，则需要更新晋级赛的人员名单s
  private async updateGroupPlayerScores(
    curMatchInfo: MatchInfo,
    stageInfo: Stage,
  ) {
    // 更新groupPlayerScore 数据，
    // 1. 找到match 对应的group
    const eventType = curMatchInfo.event?.type || curMatchInfo.type;
    const isTeamMatch = TeamEventList.includes(eventType);
    const changeGroup = stageInfo.groups.find((group) => {
      return group.id === curMatchInfo.groupId;
    });
    const newGroupPlayerScores: Array<GroupPlayerScore> =
      matchScoreHelper.getMatchScore(
        changeGroup as Group,
        isTeamMatch ? 'team' : 'single',
      );
    await this.groupPlayerScoreService.removeByGroupId(changeGroup.id);
    const savedGroupScoreList =
      await this.groupPlayerScoreService.saveList(newGroupPlayerScores);
    changeGroup.groupPlayerScores = savedGroupScoreList;
    return savedGroupScoreList;
  }
}
